<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <title>我的电视</title>
    <link href="./index_css.css" rel="stylesheet" />
    <script src="./index_js.js"></script>

    <style>
        .van-theme-dark body {
            color: #f5f5f5;
            background-color: black;
        }
    </style>
</head>

<body>
    <div class="min-h-100vh py-46px" id="app">
        <van-config-provider :theme="isDark ? 'dark' : undefined">
            <template v-if="settings">
                <div class="p-20px pt-0">
                    <div class="ml-16px text-32px">{{ settings.appTitle }}</div>
                    <div class="ml-16px text-gray text-14px">{{ settings.appRepo }}</div>
                </div>

                <template v-if="tabActive === 'config'">
                    <van-cell-group inset title="通知">
                        <van-cell title="修改之前请先关闭应用的设置界面，否则会有冲突"></van-cell>
                        <van-cell title="以下设置修改后，需要重启应用生效"></van-cell>
                    </van-cell-group>

                    <van-cell-group inset title="直播源">
                        <van-cell title="自定义直播源">
                            <template #label>
                                <van-space class="w-full" direction="vertical" size="small">
                                    <span>支持m3u链接与tvbox链接</span>
                                    <van-field class="!p-0" placeholder="置为空时，将恢复默认"
                                        v-model="settings.iptvSourceUrl" type="textarea" rows="2"></van-field>
                                </van-space>
                            </template>

                            <template #extra>
                                <van-button @click="settings.iptvSourceCachedAt = 0; confirmSettings()" size="small"
                                    type="primary">推送链接
                                </van-button>
                            </template>
                        </van-cell>
                    </van-cell-group>

                    <van-cell-group inset title="节目单">
                        <van-cell title="自定义节目单">
                            <template #label>
                                <van-space class="w-full" direction="vertical" size="small">
                                    <span>支持xml、xml.gz格式</span>
                                    <van-field class="!p-0" placeholder="置为空时，将恢复默认"
                                        v-model="settings.epgXmlUrl" type="textarea" rows="2"></van-field>
                                </van-space>
                            </template>

                            <template #extra>
                                <van-button
                                    @click="settings.epgXmlCachedAt = 0; settings.epgCachedHash = 0; confirmSettings()"
                                    size="small" type="primary">推送链接
                                </van-button>
                            </template>
                        </van-cell>
                    </van-cell-group>

                    <van-cell-group inset title="播放器">
                        <van-cell title="自定义UA">
                            <template #label>
                                <van-space class="w-full" direction="vertical" size="small">
                                    <van-field class="!p-0" placeholder="置为空时，将恢复默认"
                                            v-model="settings.videoPlayerUserAgent" type="textarea" rows="2"></van-field>
                                </van-space>
                            </template>

                            <template #extra>
                                <van-button
                                        @click="settings.epgXmlCachedAt = 0; settings.epgCachedHash = 0; confirmSettings()"
                                        size="small" type="primary">推送
                                </van-button>
                            </template>
                        </van-cell>
                    </van-cell-group>

                    <van-cell-group inset title="调试">
                        <van-cell title="上传apk">
                            <template #extra>
                                <van-uploader :after-read="uploaderAfterRead" accept=".apk" />
                            </template>
                        </van-cell>
                    </van-cell-group>
                </template>

                <template v-else-if="tabActive === 'log'">
                    <van-list>
                        <van-cell v-for="item in settings.logHistory" :key="item.time" :label="item.cause">
                            <template #title>
                                <div class="flex flex-col gap-1">
                                    <div class="flex gap-1 items-center">
                                        <van-tag plain>{{ item.tag }}</van-tag>
                                        <van-tag plain>{{ item.level }}</van-tag>
                                    </div>
                                    <span>{{ item.message }}</span>
                                </div>
                            </template>

                            <template #extra>
                                <span text="gray">{{ dayjs(item.time).format('HH:mm:ss') }}</span>
                            </template>
                        </van-cell>
                    </van-list>
                </template>

                <van-tabbar v-model="tabActive">
                    <van-tabbar-item name="config" icon="tv-o">配置</van-tabbar-item>
                    <van-tabbar-item name="log" icon="list-switch">日志</van-tabbar-item>
                </van-tabbar>
            </template>

            <van-empty image="network" v-else />
        </van-config-provider>
    </div>

    <script>
        const { createApp, ref, onMounted, watch, nextTick } = Vue

        //const baseUrl = "http://127.0.0.1:10481"
        const baseUrl = ""

        async function requestApi(url, config) {
            const resp = await fetch(`${baseUrl}${url}`, config)
            if (resp.status !== 200) {
                throw new Error(`请求失败：${resp.status}`)
            }

            return resp
        }

        dayjs.locale('zh-cn')
        dayjs.extend(dayjs_plugin_relativeTime)

        createApp({
            setup() {
                const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

                const tabActive = ref('config')

                const settings = ref()
                async function confirmSettings() {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        await requestApi('/api/settings', {
                            method: "POST",
                            body: JSON.stringify({ ...settings.value, logHistory: undefined }),
                            headers: { 'Content-Type': 'application/json' }
                        })
                        await refreshSettings()
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('无法修改设置')
                        console.error(e)
                        refreshSettings()
                    }
                }
                async function refreshSettings() {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        settings.value = await (await requestApi('/api/settings')).json()
                        settings.value.logHistory = settings.value.logHistory.reverse()
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('无法获取设置')
                        console.error(e)
                    }
                }


                onMounted(async () => {
                    await refreshSettings()
                })

                async function uploaderAfterRead(file) {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        const formData = new FormData()
                        formData.append('filename', file.file)
                        await requestApi('/api/upload/apk', { method: "POST", body: formData })
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('上传apk失败')
                        console.error(e)
                    }
                }

                return {
                    dayjs,
                    isDark,
                    tabActive,
                    settings,
                    confirmSettings,
                    uploaderAfterRead,
                }
            }
        })
            .use(vant)
            .mount('#app')
    </script>
</body>

</html>
